<template>
  <div class="createPay">
    <div>
      <el-button type="primary" size="mini" @click="newlyAdjustment">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.billType')">
            <el-select
              v-model="subDetails.fbilltypeid"
              placeholder="请选择"
            >
              <el-option
                v-for="item in billtypes"
                :key="item.fid"
                :label="item.fname"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="创建组织">-->
          <!--            <el-select v-model.trim="subDetails.fcreateorgid" @change="saleHeadel">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.bank')">
            <el-select v-model.trim="subDetails.fbankid" filterable>
              <el-option
                v-for="option in account1"
                :key="option.fid"
                :label="option.fname"
                :value="option.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.bankcode')">
            <el-input v-model="subDetails.fbankaccount">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="bankShow('', 2)"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.accountname1')">
            <el-input v-model.trim="subDetails.fbankaccountname" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.currency2')">
            <el-input v-model="subDetails.fcurrencyname">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openCurrency=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.onsetDate')">
            <el-date-picker
              v-model.trim="subDetails.fdate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.endData')">
            <el-date-picker
              v-model.trim="subDetails.fenddate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.firstbalance')">
            <el-input v-model.trim="subDetails.ffirstbalance" @change="tableData[0].fbalance=subDetails.ffirstbalance" />
          </el-form-item>
          <el-form-item :label="$t('market.finalbalance')">
            <el-input v-model.trim="subDetails.ffinalbalance" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.totaldebitamount')">
            <el-input v-model.trim="subDetails.ftotaldebitamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.totalcreditamount')">
            <el-input v-model.trim="subDetails.ftotalcreditamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.debitnum')">
            <el-input v-model.trim="subDetails.fdebitnum" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.creditnum')">
            <el-input v-model.trim="subDetails.fcreditnum" disabled />
          </el-form-item>
        </el-form>
        <div class="table-content">
          <div style="margin-bottom: 5px;">
            <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
            <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            :table-height="tableHeight"
            serial
            @rowClick="rowClick"
            @cellClick="cellClick"
          >
            <el-table-column :label="$t('market.businessDate')" align="center" width="120">
              <template slot-scope="scope">
                <el-date-picker
                  v-model.trim="scope.row.fentrydate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.amountIn')" align="center" width="80px">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fdebitamount"
                  :min="0"
                  size="mini"
                  @change="scope.row.fcreditamount=0"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.amountOut')" align="center" width="80px">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fcreditamount"
                  :min="0"
                  size="mini"
                  @change="scope.row.fdebitamount=0"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.money')" align="center" width="80px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.fbalance" disabled size="mini" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.digest')" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.fabstract" size="mini" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.settleType')" align="center" width="150px" prop="fsettleid">
              <template slot-scope="scope">
                <el-select v-model.trim="scope.row.fsettleid" filterable>
                  <el-option
                    v-for="option in account2"
                    :key="option.fid"
                    :label="option.fname"
                    :value="option.fid"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.settlementnum')" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.fnum" size="mini" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.othersbankname')" align="center" width="150px" prop="fbanknameid">
              <template slot-scope="scope">
                <el-select v-model.trim="scope.row.fothersbankname" filterable>
                  <el-option
                    v-for="option in account1"
                    :key="option.fid"
                    :label="option.fname"
                    :value="option.fid"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.othersbankaccount')" align="center" width="170px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fothersbankaccount">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="bankShow(scope.$index, 1)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.othersaccountname')" align="center" width="150px" prop="fothersaccountname" />
          </jc-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!--币别-->
    <currency v-if="openCurrency" @currency="currencySelectRow" />
    <!--银行账号-->
    <bank v-if="bankVisiblit" @client="bankData" />
  </div>
</template>

<script>
import { queryOrgDetail, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import bility from '@/mixin/Operability'
import { createBankCheckBill } from '@/api/financial/teller'

export default {
  name: 'StatementAdd',
  components: {
    bank: () => import('@/views/financial/cashier/payment/component/bank'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency')
  },
  mixins: [autocomplete, bility],
  data() {
    return {
      account1: [], // 银行
      account2: [], // 结算方式
      bankVisiblit: false, // 银行账号
      openCurrency: false, // 币别、价目表、价格类型
      subDetails: {
        fcreateorgid: 1,
        fdocumentstatus: 'A',
        fbilltypeid: 1362,
        fdate: new Date(),
        fbankid: 1328,
        fcreditnum: '',
        ffirstbalance: '',
        ftotalcreditamount: '',
        fenddate: new Date(),
        ftotaldebitamount: '',
        fdebitnum: '',
        ffinalbalance: '',
        fbankaccountname: ''
      },
      activeName: 'first',
      billtypes: [], // 单据类型
      indexSelf: 0,
      // 表头
      tableData: [{
        fentrydate: new Date(),
        fdebitamount: 0, fcreditamount: 0,
        fbalance: '', fsettleid: 91,
        fabstract: '', fnum: '',
        fothersbankname: '', fothersbankaccount: ''
      }], // 银行转账单数据
      tableHeight: '70vh',
      tableHeader: []
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.subDetails.ftotaldebitamount = 0 // 借方合计金额
        this.subDetails.ftotalcreditamount = 0 // 贷方合计金额
        this.subDetails.fdebitnum = 0 // 借方笔数
        this.subDetails.fcreditnum = 0 // 贷方笔数
        val.forEach((res, index) => {
          if (res.fdebitamount > 0) { // 借方金额
            this.subDetails.fdebitnum += 1
            this.subDetails.ftotaldebitamount += res.fdebitamount
            // 余额 = 上一级余额 +(贷方金额)或 - (借方金额)
            // 第一行余额 = 首笔余额  最后一行余额=末笔余额
            index > 0 ? res.fbalance = this.tableData[index - 1].fbalance - res.fdebitamount : ''
          } else if (res.fcreditamount > 0) { // 贷方金额
            this.subDetails.fcreditnum += 1
            this.subDetails.ftotalcreditamount += res.fcreditamount
            index > 0 ? res.fbalance = this.tableData[index - 1].fbalance + res.fcreditamount : ''
          }
        })
        this.subDetails.ffinalbalance = val[val.length - 1].fbalance
      },
      deep: true
    }
  },
  created() {
    this.queryTBasBilltype()
    this.queryTBasBilltype1()
    this.saleHeadel()
    this.getForm()
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 320px)' : '73vh'
  },
  methods: {
    // 监听组织
    saleHeadel() {
      const forgids = this.subDetails.fcreateorgid
      queryOrgDetail({ forgids }).then(res => {
        if (res.code === 0) {
          this.subDetails = {
            ...this.subDetails,
            fcurrencyname: res.data.flocalCurr, // 币别
            fcurrencyid: res.data.flocalCurrId // 币别id
          }
        }
      })
    },
    // 保存
    newlyAdjustment() {
      const DATA = {
        ...this.subDetails,
        details: this.tableData
      }
      createBankCheckBill(DATA).then(res => {
        if (res.code === 0) {
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: `/statementDetail/${res.data.fid}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 开户银行数据
    async getForm() {
      await queryViewItem({ viewName: 'SX_FIN_BANK' }).then(res => {
        this.account1 = res.data.list
      })
    },
    // 查询结算方式
    async queryTBasBilltype1() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_SETTLETYPE' })
      this.account2 = RES.list
    },
    // 查询单据类型
    async queryTBasBilltype() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_FIN_BANK_CHECK' })
      this.billtypes = RES.list
    },
    // 银行弹窗
    bankShow(index, ev) {
      this.outIn = ev
      this.indexSelf = index
      this.bankVisiblit = true
    },
    bankData(ev) {
      if (ev.fbankaccountId && this.outIn === 1) { // 表格
        const item = this.tableData[this.indexSelf]
        item.fothersbankaccountid = ev.fbankaccountId
        item.fothersbankaccount = ev.faccount
        item.fothersaccountname = ev.faccountname
      } else if (ev.fbankaccountId && this.outIn === 2) { // 表头
        this.subDetails.fbankaccountid = ev.fbankaccountId
        this.subDetails.fbankaccount = ev.faccount
        this.subDetails.fbankaccountname = ev.faccountname
      }
      this.bankVisiblit = false
    },
    // 币别选中
    currencySelectRow(ev) {
      const item = this.subDetails
      if (ev.fsettleCurrId) { // 转入
        item.fcurrencyid = ev.fsettleCurrId
        item.fcurrencyname = ev.fsettleCurrIdName
      }
      this.openCurrency = false
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      const leg = this.tableData.length
      this.tableData.push({
        fentrydate: this.subDetails.fdate,
        fdebitamount: 0, fcreditamount: 0,
        fbalance: leg === 0 ? this.subDetails.ffirstbalance : 0,
        fsettleid: 91,
        fabstract: '', fnum: '',
        fothersbankname: '', fothersbankaccount: ''
      })
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999!important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left:0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
.createPay {
  @include listBom;
  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
  .el-table{
    &::v-deep .el-input-number .el-input__inner{
      padding: 0;
      width: 75px;
    }
    &::v-deep .el-input-number .el-input{
      width: 75px;
    }
    &::v-deep .el-input-number--mini{
      width: 75px
    }
    &::v-deep .el-input-number__increase{
      display: none;
    }
    &::v-deep .el-input-number__decrease{
      display: none;
    }
    &::v-deep .el-table__footer-wrapper tbody td{
      background: #fdf6ec!important;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 268px;
      margin-bottom: 2px;

      .btnType {
        margin-right: 20px;
      }

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
